<?php

declare(strict_types=1);

namespace App\Traits\Model\Admin;


use App\Constants\Admin\AdminLogCode;
use App\Model\Admin\Admin as AdminModel;
use App\Request\FormRequest;
use App\Scopes\Admin\AdminLog as AdminLogScope;
use Hyperf\Context\Context;
use Hyperf\Collection\Arr;
use function Hyperf\Support\make;

trait AdminLog
{
    /**
     * The "booting" method of the model.
     */
    protected function boot():void
    {
        parent::boot();
        static::addGlobalScope(new AdminLogScope);
    }

    /**
     * 设置应用
     * @param $value
     */
    public function setAppAttribute($value)
    {
        $request = make(FormRequest::class);
        $this->attributes['app'] = $request->appName();
    }

    /**
     * 设置IP
     * @param $value
     */
    public function setIpAttribute($value):void
    {
        $request = make(FormRequest::class);
        $this->attributes['ip'] = ip2long($request->ip());
    }

    /**
     * 设置用户代理
     * @param $value
     */
    public function setUserAgentAttribute($value)
    {
        $request = make(FormRequest::class);
        $this->attributes['user_agent'] = $request->header('user-agent');
    }

    /**
     * 设置管理员
     * @param $value
     * @return array|\ArrayAccess|mixed
     */
    public function setAdminIdAttribute($value)
    {
        $request = make(FormRequest::class);
        $app = $request->appName();
        $paramName = "{$app}Info";
        $info = Context::get($paramName);
        $this->attributes['admin_id'] = Arr::get($info, 'id', 0);
    }

    /**
     * 新增日志
     * @param int $type
     * @param string $desc
     * @param string $modular
     * @param int $outId
     * @param string $model
     * @return \App\Model\Admin\AdminLog|AdminLog|\Hyperf\Database\Model\Model
     */
    public static function add(int $type, string $desc, string $modular='', $outId=0, string $model='')
    {
        $model = self::create([
            'type' => $type,
            'desc' => $desc,
            'out_id' => $outId,
            'model' => $model,
            'modular' => $modular
        ]);

        return $model;
    }

    /**
     * 管理员关联
     * @return \Hyperf\Database\Model\Relations\BelongsTo
     */
    public function admin()
    {
        return $this->belongsTo(AdminModel::class);
    }

    /**
     * 获取描述详情
     * @param $value
     */
    public function getDescTextAttribute($value)
    {
        $request = make(FormRequest::class);
        $appName = $request->appName();
        $app = $this->$appName;
        $nickname = $app?($app->nickname?:$app->username):'已删除';
        $modularText = $this->attributes['modular']?"[{$this->attributes['modular']}]":'';
        $idText = $this->attributes['out_id']?"ID:[{$this->attributes['out_id']}]":'';
        $typeMessage = AdminLogCode::getMessage($this->attributes['type']);

        return "管理员:[{$nickname}]{$typeMessage}{$modularText}{$idText}{$this->attributes['desc']}";
    }
}
